package com.aiyige.page.publish.traingclass;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.eventbus.EventCopyTraingClassFinish;
import com.aiyige.base.eventbus.EventEditTraingClassFinish;
import com.aiyige.page.publish.CommonTipDialog;
import com.aiyige.page.publish.adapter.FormTagAdapter;
import com.aiyige.page.publish.adapter.FormTraingCardAdapter;
import com.aiyige.page.publish.courseschedule.CourseSchedulePage;
import com.aiyige.page.publish.courseschedule.model.CourseScheduleModel;
import com.aiyige.page.publish.selectinterest.PublishSelectInterestPage;
import com.aiyige.page.publish.selectinterest.model.PublishIndustryItem;
import com.aiyige.page.publish.selectinterest.model.PublishInterestItem;
import com.aiyige.page.publish.selectlearntarget.SelectLearnTargetPage;
import com.aiyige.page.publish.selectlearntarget.model.SelectLearnTargetItem;
import com.aiyige.page.publish.selectlocation.SelectLocationPage;
import com.aiyige.page.publish.selectlocation.model.SelectLocationData;
import com.aiyige.page.publish.selectsuitablelearnage.SelectSuitableLearnAgePage;
import com.aiyige.page.publish.selectsuitablelearnage.model.SuitableLearnAgeItem;
import com.aiyige.page.publish.selectsuitablepeople.SelectSuitablePeoplePage;
import com.aiyige.page.publish.selectsuitablepeople.model.SelectSuitablePeopleItem;
import com.aiyige.page.publish.selecttag.SelectTagPage;
import com.aiyige.page.publish.selecttag.model.SelectTagItem;
import com.aiyige.page.publish.selecttraingcard.SelectTraingCardPage;
import com.aiyige.page.publish.selecttraingcard.model.TraingCard;
import com.aiyige.page.publish.traingclass.model.ClassLocation;
import com.aiyige.page.publish.traingclass.model.TraingClassFormModel;
import com.aiyige.page.publish.util.PublishUtil;
import com.aiyige.utils.CancelEditDialogUtil;
import com.aiyige.utils.ColorUtil;
import com.aiyige.utils.DateFormatUtil;
import com.aiyige.utils.ExcludeEmojiInputFilter;
import com.aiyige.utils.ExcludeSpaceInputFilter;
import com.aiyige.utils.InputNumFilter;
import com.aiyige.utils.KeyboardUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.TextWatcherAdapter;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.UIHelper;
import com.aiyige.utils.exception.FormFieldException;
import com.aiyige.utils.widget.CommonBottomDialogFragment;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bigkoo.pickerview.TimePickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;

import net.cachapa.expandablelayout.ExpandableLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

@Route(path = ARouterConfig.PublishTraingClassFormPage, extras = ARouterConfig.EXTRA_NEED_LOGIN | ARouterConfig.EXTRA_NEED_BINDPHONE)
public class PublishTraingClassFormPage extends AppCompatActivity {
    public static final int REQUEST_CODE_SELECT_INTEREST = 1;
    public static final int REQUEST_CODE_SELECT_SUITABLE_LEARN_AGE = 2;
    public static final int REQUEST_CODE_SELECT_LEARN_TARGET = 3;
    public static final int REQUEST_CODE_SELECT_SUITABLE_PEOPLE = 4;
    public static final int REQUEST_CODE_SELECT_TAG = 5;
    public static final int REQUEST_CODE_SELECT_TRAING_CARD = 6;
    public static final int REQUEST_CODE_SELECT_CLASS_LOCATION = 7;
    public static final int REQUEST_CODE_INPUT_COURSE_SCHEDULE = 8;
    public static final int REQUEST_CODE_NEXT = 9;
    @Autowired
    TraingClassFormModel formModel = null;

    CommonBottomDialogFragment openBuyDialog;
    CommonBottomDialogFragment openClassConditionDialog;
    FormTagAdapter formTagAdapter;
    FormTraingCardAdapter formTraingCardAdapter;
    @BindView(R.id.containerLayout)
    View containerLayout;
    @BindView(R.id.titleBackBtn)
    ImageView titleBackBtn;
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.titleEt)
    EditText titleEt;
    @BindView(R.id.formTitleLayout)
    ViewGroup formTitleLayout;
    @BindView(R.id.interestTv)
    TextView interestTv;
    @BindView(R.id.interestLayout)
    RelativeLayout interestLayout;
    @BindView(R.id.openBuyTv)
    TextView openBuyTv;
    @BindView(R.id.view)
    View view;
    @BindView(R.id.openBuyLayout)
    RelativeLayout openBuyLayout;
    @BindView(R.id.classSizeEt)
    EditText classSizeEt;
    @BindView(R.id.classSizeLayout)
    RelativeLayout classSizeLayout;
    @BindView(R.id.openClassConditionTv)
    TextView openClassConditionTv;
    @BindView(R.id.openClassConditionLayout)
    RelativeLayout openClassConditionLayout;
    @BindView(R.id.startClassDateTv)
    TextView startClassDateTv;
    @BindView(R.id.startClassDateLayout)
    RelativeLayout startClassDateLayout;
    @BindView(R.id.endClassDateTv)
    TextView endClassDateTv;
    @BindView(R.id.endClassDateLayout)
    RelativeLayout endClassDateLayout;
    @BindView(R.id.minClassSizeEt)
    EditText minClassSizeEt;
    @BindView(R.id.minClassSizeLayout)
    RelativeLayout minClassSizeLayout;
    @BindView(R.id.confirmDateTv)
    TextView confirmDateTv;
    @BindView(R.id.confirmDateLayout)
    RelativeLayout confirmDateLayout;
    @BindView(R.id.minClassSizeContainer)
    ExpandableLayout minClassSizeContainer;
    @BindView(R.id.classLocationTv)
    TextView classLocationTv;
    @BindView(R.id.classLocationLayout)
    RelativeLayout classLocationLayout;
    @BindView(R.id.suitableLearnAgeTv)
    TextView suitableLearnAgeTv;
    @BindView(R.id.suitableLearnAgeLayout)
    RelativeLayout suitableLearnAgeLayout;
    @BindView(R.id.learnTargetTv)
    TextView learnTargetTv;
    @BindView(R.id.learnTargetLayout)
    RelativeLayout learnTargetLayout;
    @BindView(R.id.suitableLearnPeopleTv)
    TextView suitableLearnPeopleTv;
    @BindView(R.id.suitableLearnPeopleLayout)
    RelativeLayout suitableLearnPeopleLayout;
    @BindView(R.id.priceEt)
    EditText priceEt;
    @BindView(R.id.priceLayout)
    RelativeLayout priceLayout;
    @BindView(R.id.courseNumberEt)
    EditText courseNumberEt;
    @BindView(R.id.courseNumberLayout)
    RelativeLayout courseNumberLayout;
    @BindView(R.id.singleClassDurationEt)
    EditText singleClassDurationEt;
    @BindView(R.id.singleClassDurationLayout)
    RelativeLayout singleClassDurationLayout;
    @BindView(R.id.platformDividendEt)
    EditText platformDividendEt;
    @BindView(R.id.platformDividendLayout)
    RelativeLayout platformDividendLayout;
    @BindView(R.id.platformDividendDescContainer)
    ExpandableLayout platformDividendDescContainer;
    @BindView(R.id.tagTv)
    TextView tagTv;
    @BindView(R.id.tagRv)
    RecyclerView tagRv;
    @BindView(R.id.tagLayout)
    RelativeLayout tagLayout;
    @BindView(R.id.traingCardTv)
    TextView traingCardTv;
    @BindView(R.id.traingCardRv)
    RecyclerView traingCardRv;
    @BindView(R.id.traingCardLayout)
    RelativeLayout traingCardLayout;
    @BindView(R.id.singleClassPriceEt)
    EditText singleClassPriceEt;
    @BindView(R.id.singleClassPriceLayout)
    RelativeLayout singleClassPriceLayout;
    @BindView(R.id.singleClassPriceContainer)
    ExpandableLayout singleClassPriceContainer;
    @BindView(R.id.nextBtn)
    TextView nextBtn;
    KeyboardUtil.KeyboardMonitor keyboardMonitor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_publish_traing_class_form);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        if (formModel == null) {
            finish();
            return;
        }
        switch (formModel.getOperationType()) {
            case PublishUtil.OPERATION_TYPE_EDIT:
                titleTv.setText(R.string.edit_traing_class);
                break;
            default:
                titleTv.setText(R.string.publish_traing_class);
                break;
        }
        initView();
        updateView();
    }

    @Override
    protected void onDestroy() {
        keyboardMonitor.uninstall();
        super.onDestroy();
    }

    void initView() {
        keyboardMonitor = KeyboardUtil.KeyboardMonitor.newBuilder()
                .container(containerLayout)
                .callback(new KeyboardUtil.KeyboardMonitor.Callback() {
                    @Override
                    public void onKeyboardShow() {
                        nextBtn.setVisibility(View.INVISIBLE);
                    }

                    @Override
                    public void onKeyboardHide() {
                        nextBtn.setVisibility(View.VISIBLE);
                        containerLayout.requestFocus();
                    }
                })
                .build()
                .install();
        titleEt.setFilters(new InputFilter[]{new ExcludeSpaceInputFilter(), new ExcludeEmojiInputFilter(), new InputNumFilter(30, false)});
        tagRv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        formTagAdapter = new FormTagAdapter();
        formTagAdapter.bindToRecyclerView(tagRv);
        formTagAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.deleteBtn:
                        adapter.remove(position);
                        break;
                }
            }
        });
        traingCardRv.setLayoutManager(new GridLayoutManager(this, 3));
        formTraingCardAdapter = new FormTraingCardAdapter();
        formTraingCardAdapter.bindToRecyclerView(traingCardRv);
        formTraingCardAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.deleteBtn:
                        adapter.remove(position);
                        break;
                }
            }
        });

        titleEt.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void afterTextChanged(Editable s) {
                formModel.setTitle(s.toString());
            }
        });

        classSizeEt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    try {
                        int value;
                        try {
                            value = Integer.parseInt(classSizeEt.getText().toString());
                        } catch (Exception e) {
                            throw new FormFieldException(R.string.invalid_integer);
                        }

                        if (value <= 0) {
                            throw new FormFieldException(R.string.invalid_integer);
                        }
                        int minClassSizeValue = Integer.MIN_VALUE;
                        try {
                            minClassSizeValue = Integer.parseInt(formModel.getMinClassSize());
                        } catch (Exception e) {

                        }
                        if (value < minClassSizeValue) {
                            throw new FormFieldException(R.string.class_size_not_less_than_min_class_size);
                        }
                        formModel.setClassSize(String.valueOf(value));
                    } catch (Exception e) {
                        ToastX.show(e.getMessage());
                        formModel.setClassSize(null);
                    }
                    updateView();
                }
            }
        });

        minClassSizeEt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    try {
                        int value;
                        try {
                            value = Integer.parseInt(minClassSizeEt.getText().toString());
                        } catch (Exception e) {
                            throw new FormFieldException(R.string.invalid_integer);
                        }
                        if (value <= 0) {
                            throw new FormFieldException(R.string.invalid_integer);
                        }
                        int classSizeValue = Integer.MAX_VALUE;
                        try {
                            classSizeValue = Integer.parseInt(formModel.getClassSize());
                        } catch (Exception e) {

                        }
                        if (value > classSizeValue) {
                            throw new FormFieldException(R.string.min_class_size_not_greater_than_class_size);
                        }
                        formModel.setMinClassSize(String.valueOf(value));
                    } catch (Exception e) {
                        ToastX.show(e.getMessage());
                        formModel.setMinClassSize(null);
                    }
                    updateView();
                }
            }
        });

        priceEt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    try {
                        String valueStr = priceEt.getText().toString().trim();
                        double value = Double.parseDouble(valueStr);
                        if (value < 0) {
                            throw new Exception();
                        }
                        formModel.setPrice(StringUtils.priceFormatEscapeRedundantTailZero(value));
                    } catch (Exception e) {
                        ToastX.show(R.string.invalid_price);
                        formModel.setPrice(null);
                    }
                    updateView();
                }
            }
        });

        courseNumberEt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    try {
                        int value = Integer.parseInt(courseNumberEt.getText().toString());
                        if (value <= 0) {
                            throw new Exception();
                        }
                        formModel.setCourseNumber(String.valueOf(value));
                    } catch (Exception e) {
                        ToastX.show(R.string.invalid_integer);
                        formModel.setCourseNumber(null);
                    }
                    updateView();
                }
            }
        });

        singleClassDurationEt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    try {
                        int value = Integer.parseInt(singleClassDurationEt.getText().toString());
                        if (value <= 0) {
                            throw new Exception();
                        }
                        formModel.setSingleClassDuration(String.valueOf(value));
                    } catch (Exception e) {
                        ToastX.show(R.string.invalid_integer);
                        formModel.setSingleClassDuration(null);
                    }
                    updateView();
                }
            }
        });

        platformDividendEt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    try {
                        String valueStr = platformDividendEt.getText().toString().trim();
                        double dividend = Double.parseDouble(valueStr);
                        if (dividend / 100 < PublishUtil.MIN_PLATFORM_DIVIDEND) {
                            throw new Exception("");
                        }
                        if (dividend / 100 > 1) {
                            throw new Exception("");
                        }
                        formModel.setPlatformDividend(StringUtils.priceFormatEscapeRedundantTailZero(dividend));
                    } catch (Exception e) {
                        ToastX.show(R.string.invalid_platform_dividend);
                        formModel.setPlatformDividend(null);
                    }
                    updateView();
                }
            }
        });

        singleClassPriceEt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    try {
                        String valueStr = singleClassPriceEt.getText().toString().trim();
                        double value = Double.parseDouble(valueStr);
                        if (value < 0) {
                            throw new Exception();
                        }
                        formModel.setSinglePrice(StringUtils.priceFormatEscapeRedundantTailZero(value));
                    } catch (Exception e) {
                        ToastX.show(R.string.invalid_price);
                        formModel.setSinglePrice(null);
                    }
                    updateView();
                }
            }
        });


        openBuyDialog = CommonBottomDialogFragment.newBuilder()
                .layoutResId(R.layout.open_buy_dialog)
                .viewIdList(R.id.yesBtn, R.id.noBtn, R.id.cancelBtn)
                .listener(new CommonBottomDialogFragment.Listener() {
                    @Override
                    public void onViewClicked(int position, View view) {
                        switch (view.getId()) {
                            case R.id.yesBtn:
                                formModel.setOpenBuy(true);
                                break;
                            case R.id.noBtn:
                                formModel.setOpenBuy(false);
                                break;
                        }
                        updateView();
                    }
                })
                .build();
        openClassConditionDialog = CommonBottomDialogFragment.newBuilder()
                .layoutResId(R.layout.open_class_condition_dialog)
                .viewIdList(R.id.dependOnOpenDateBtn, R.id.dependOnPopulationBtn, R.id.cancelBtn)
                .listener(new CommonBottomDialogFragment.Listener() {
                    @Override
                    public void onViewClicked(int position, View view) {
                        switch (view.getId()) {
                            case R.id.dependOnOpenDateBtn:
                                formModel.setOpenClassCondition(TraingClassFormModel.OPEN_CLASS_CONDITION_DEPEND_ON_OPEN_DATE);
                                break;
                            case R.id.dependOnPopulationBtn:
                                formModel.setOpenClassCondition(TraingClassFormModel.OPEN_CLASS_CONDITION_DEPEND_ON_POPULATION);
                                break;
                        }
                        updateView();
                    }
                })
                .build();
    }

    public void updateView() {
        titleEt.setText(formModel.getTitle());
        if (formModel.getPublishInterestItem() != null) {
            interestTv.setText(formModel.getPublishInterestItem().getTitle());
        } else {
            interestTv.setText("");
        }

        if (formModel.getPublishInterestItem() != null && !TextUtils.isEmpty(formModel.getPublishInterestItem().getParent().getId())) {
            enableTagSelect();
        } else {
            disableTagSelect();
        }

        if (formModel.getOpenBuy() != null) {
            openBuyTv.setText(formModel.getOpenBuy() ? R.string.yes : R.string.no);
        } else {
            openBuyTv.setText("");
        }
        classSizeEt.setText(formModel.getClassSize());
        if (formModel.getOpenClassCondition() != null) {
            switch (formModel.getOpenClassCondition()) {
                case TraingClassFormModel.OPEN_CLASS_CONDITION_DEPEND_ON_OPEN_DATE:
                    openClassConditionTv.setText(R.string.open_class_depend_on_open_date);
                    minClassSizeContainer.collapse();
                    break;
                case TraingClassFormModel.OPEN_CLASS_CONDITION_DEPEND_ON_POPULATION:
                    openClassConditionTv.setText(R.string.open_class_depend_on_population);
                    minClassSizeContainer.expand();
                    break;
            }
        } else {
            openClassConditionTv.setText("");
            minClassSizeContainer.collapse(false);
        }
        if (formModel.getStartClassDate() != null) {
            startClassDateTv.setText(DateFormatUtil.formatMS("yyyy-MM-dd", formModel.getStartClassDate()));
        } else {
            startClassDateTv.setText("");
        }
        if (formModel.getEndClassDate() != null) {
            endClassDateTv.setText(DateFormatUtil.formatMS("yyyy-MM-dd", formModel.getEndClassDate()));
        } else {
            endClassDateTv.setText("");
        }
        if (formModel.getMinClassSize() != null) {
            minClassSizeEt.setText(formModel.getMinClassSize());
        } else {
            minClassSizeEt.setText("");
        }
        if (formModel.getConfirmDate() != null) {
            confirmDateTv.setText(DateFormatUtil.formatMS("yyyy-MM-dd", formModel.getConfirmDate()));
        } else {
            confirmDateTv.setText("");
        }
        if (formModel.getClassLocation() != null) {
            classLocationTv.setText(formModel.getClassLocation().getProvince() + " " + formModel.getClassLocation().getCity());
        } else {
            classLocationTv.setText("");
        }
        if (!ListUtil.isEmpty(formModel.getSuitableLearnAgeItemList())) {
            suitableLearnAgeTv.setText(TextUtils.join("、", formModel.getSuitableLearnAgeItemList()));
        } else {
            suitableLearnAgeTv.setText("");
        }
        if (!ListUtil.isEmpty(formModel.getSelectLearnTargetItemList())) {
            learnTargetTv.setText(TextUtils.join("、", formModel.getSelectLearnTargetItemList()));
        } else {
            learnTargetTv.setText("");
        }
        if (formModel.getSelectSuitablePeopleItem() != null) {
            suitableLearnPeopleTv.setText(formModel.getSelectSuitablePeopleItem().getTitle());
        } else {
            suitableLearnPeopleTv.setText("");
        }
        if (formModel.getPrice() != null) {
            priceEt.setText(formModel.getPrice());
        } else {
            priceEt.setText("");
        }

        if (formModel.getCourseNumber() != null) {
            courseNumberEt.setText(formModel.getCourseNumber());
        } else {
            courseNumberEt.setText("");
        }
        if (formModel.getSingleClassDuration() != null) {
            singleClassDurationEt.setText(formModel.getSingleClassDuration());
        } else {
            singleClassDurationEt.setText("");
        }
        if (formModel.getPlatformDividend() != null) {
            platformDividendEt.setText(formModel.getPlatformDividend());
        } else {
            platformDividendEt.setText("");
        }
        formTagAdapter.setNewData(formModel.getSelectTagItemList());
        formTraingCardAdapter.setNewData(formModel.getTraingCardList());
        if (ListUtil.isEmpty(formModel.getSelectTagItemList())) {
            tagTv.setVisibility(View.VISIBLE);
        } else {
            tagTv.setVisibility(View.INVISIBLE);
        }
        if (ListUtil.isEmpty(formModel.getTraingCardList())) {
            traingCardTv.setVisibility(View.VISIBLE);
        } else {
            traingCardTv.setVisibility(View.INVISIBLE);
        }
        singleClassPriceEt.setText(formModel.getSinglePrice());
        boolean havePrepaidCard = false;
        for (TraingCard traingCard : formModel.getTraingCardList()) {
            if (traingCard.getType() == TraingCard.TYPE_PREPAID_CARD) {
                havePrepaidCard = true;
                break;
            }
        }
        if (havePrepaidCard) {
            singleClassPriceContainer.expand();
        } else {
            singleClassPriceContainer.collapse();
        }
        if (formModel.getStartClassDate() == null) {
            disableDateSelect();
        } else {
            enableDateSelect();
        }
    }

    boolean checkFormValidate() {
        boolean result = true;
        if (TextUtils.isEmpty(formModel.getTitle())) {
            result = false;
            formTitleLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
        } else {
            formTitleLayout.setBackgroundResource(R.color.white);
        }


        if (TextUtils.isEmpty(formModel.getPublishInterestItem().getId())) {
            result = false;
            interestLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
        } else {
            interestLayout.setBackgroundResource(R.color.white);
        }

        if (TextUtils.isEmpty(formModel.getClassSize())) {
            result = false;
            classSizeLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
        } else {
            classSizeLayout.setBackgroundResource(R.color.white);
        }

        if (formModel.getOpenClassCondition() == null) {
            result = false;
            openClassConditionLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
        } else {
            openClassConditionLayout.setBackgroundResource(R.color.white);
        }

        if (formModel.getOpenClassCondition() != null && formModel.getOpenClassCondition() == TraingClassFormModel.OPEN_CLASS_CONDITION_DEPEND_ON_POPULATION) {
            if (TextUtils.isEmpty(formModel.getMinClassSize())) {
                result = false;
                minClassSizeLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
            } else {
                minClassSizeLayout.setBackgroundResource(R.color.white);
            }

            if (formModel.getConfirmDate() == null) {
                result = false;
                confirmDateLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
            } else {
                confirmDateLayout.setBackgroundResource(R.color.white);
            }
        }

        if (formModel.getStartClassDate() == null) {
            result = false;
            startClassDateLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
        } else {
            startClassDateLayout.setBackgroundResource(R.color.white);
        }

        if (formModel.getEndClassDate() == null) {
            result = false;
            endClassDateLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
        } else {
            endClassDateLayout.setBackgroundResource(R.color.white);
        }

        if (formModel.getClassLocation() == null) {
            result = false;
            classLocationLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
        } else {
            classLocationLayout.setBackgroundResource(R.color.white);
        }

        if (ListUtil.isEmpty(formModel.getSuitableLearnAgeItemList())) {
            result = false;
            suitableLearnAgeLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
        } else {
            suitableLearnAgeLayout.setBackgroundResource(R.color.white);
        }

        if (ListUtil.isEmpty(formModel.getSelectLearnTargetItemList())) {
            result = false;
            learnTargetLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
        } else {
            learnTargetLayout.setBackgroundResource(R.color.white);
        }

        if (formModel.getSelectSuitablePeopleItem() == null) {
            result = false;
            suitableLearnPeopleLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
        } else {
            suitableLearnPeopleLayout.setBackgroundResource(R.color.white);
        }

        if (TextUtils.isEmpty(formModel.getPrice())) {
            result = false;
            priceLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
        } else {
            priceLayout.setBackgroundResource(R.color.white);
        }

        if (TextUtils.isEmpty(formModel.getPlatformDividend())) {
            result = false;
            platformDividendLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
        } else {
            platformDividendLayout.setBackgroundResource(R.color.white);
        }

        if (TextUtils.isEmpty(formModel.getCourseNumber())) {
            result = false;
            courseNumberLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
        } else {
            courseNumberLayout.setBackgroundResource(R.color.white);
        }

//        boolean havePrepaidCard = false;
//        for (TraingCard traingCard : formModel.getTraingCardList()) {
//            if (traingCard.getType() == TraingCard.TYPE_PREPAID_CARD) {
//                havePrepaidCard = true;
//                break;
//            }
//        }
//        if (havePrepaidCard) {
//            if (TextUtils.isEmpty(formModel.getSinglePrice())) {
//                result = false;
//                singleClassPriceLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
//            } else {
//                singleClassPriceLayout.setBackgroundResource(R.color.white);
//            }
//        }
        if (!result) {
            ToastX.show(R.string.unfinish_form);
        }
        return result;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_INPUT_COURSE_SCHEDULE: {
                if (resultCode == RESULT_OK) {
                    CourseScheduleModel courseScheduleModel = data.getParcelableExtra(CourseSchedulePage.EXTRA_KEY_COURSE_SCHEDULE_DATA);
                    formModel.setCourseScheduleModel(courseScheduleModel);
                }
                break;
            }
            case REQUEST_CODE_SELECT_CLASS_LOCATION: {
                if (resultCode == RESULT_OK) {
                    SelectLocationData selectLocationData = data.getParcelableExtra(SelectLocationPage.EXTRA_KEY_SELECT_LOCATION);
                    formModel.setClassLocation(ClassLocation.newBuilder()
                            .city(selectLocationData.getCity())
                            .province(selectLocationData.getProvince())
                            .id(selectLocationData.getCityId())
                            .build());
                }
                break;
            }
            case REQUEST_CODE_SELECT_INTEREST: {
                if (resultCode == RESULT_OK) {
                    enableTagSelect();
                    if (!formModel.getPublishInterestItem().getParent().getId().equals(data.getStringExtra(PublishSelectInterestPage.EXTRA_KEY_SELECTED_PARENT_ID))) {
                        clearTagSelect();
                    }
                    formModel.setPublishInterestItem(
                            PublishInterestItem.newBuilder()
                                    .id(data.getStringExtra(PublishSelectInterestPage.EXTRA_KEY_SELECTED_ID))
                                    .title(data.getStringExtra(PublishSelectInterestPage.EXTRA_KEY_SELECTED_TITLE))
                                    .parent(PublishIndustryItem.newBuilder()
                                            .id(data.getStringExtra(PublishSelectInterestPage.EXTRA_KEY_SELECTED_PARENT_ID))
                                            .title(data.getStringExtra(PublishSelectInterestPage.EXTRA_KEY_SELECTED_PARENT_TITLE))
                                            .build())
                                    .build());
                }
                break;
            }
            case REQUEST_CODE_SELECT_LEARN_TARGET: {
                if (resultCode == RESULT_OK) {
                    List<SelectLearnTargetItem> selectLearnTargetItemList = data.getParcelableArrayListExtra(SelectLearnTargetPage.EXTRA_KEY_SELECTED_LEARN_TARGET_DATA);
                    formModel.setSelectLearnTargetItemList(selectLearnTargetItemList);
                }
                break;
            }
            case REQUEST_CODE_SELECT_SUITABLE_LEARN_AGE: {
                if (resultCode == RESULT_OK) {
                    List<SuitableLearnAgeItem> suitableLearnAgeItemList = data.getParcelableArrayListExtra(SelectSuitableLearnAgePage.EXTRA_KEY_SELECTED_SUITABLE_LEARN_AGE_DATA);
                    formModel.setSuitableLearnAgeItemList(suitableLearnAgeItemList);
                }
                break;
            }
            case REQUEST_CODE_SELECT_SUITABLE_PEOPLE: {
                if (resultCode == RESULT_OK) {
                    formModel.setSelectSuitablePeopleItem(
                            SelectSuitablePeopleItem.newBuilder()
                                    .id(data.getStringExtra(SelectSuitablePeoplePage.EXTRA_KEY_SELECTED_SUITABLE_PEOPLE_ID))
                                    .title(data.getStringExtra(SelectSuitablePeoplePage.EXTRA_KEY_SELECTED_SUITABLE_PEOPLE_TITLE))
                                    .build());
                }
                break;
            }
            case REQUEST_CODE_SELECT_TAG: {
                if (resultCode == RESULT_OK) {
                    formModel.getSelectTagItemList().add(SelectTagItem.newBuilder()
                            .id(data.getStringExtra(SelectTagPage.EXTRA_KEY_SELECTED_TAG_ID))
                            .name(data.getStringExtra(SelectTagPage.EXTRA_KEY_SELECTED_TAG_NAME))
                            .build());
                }
                break;
            }
            case REQUEST_CODE_SELECT_TRAING_CARD: {
                if (resultCode == RESULT_OK) {
                    List<TraingCard> traingCardList = data.getParcelableArrayListExtra(SelectTraingCardPage.EXTRA_KEY_SELECT_TRAING_CARD_DATA);
                    formModel.setTraingCardList(traingCardList);
                }
                break;
            }
            case REQUEST_CODE_NEXT: {
                if (resultCode == RESULT_OK) {
                    setResult(RESULT_OK, data);
                    finish();
                }
                break;
            }
            default: {
                super.onActivityResult(requestCode, resultCode, data);
                break;
            }
        }
        updateView();
    }

    @Override
    public void onBackPressed() {
        CancelEditDialogUtil.newbuilder(this)
                .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                        EventBus.getDefault().post(EventEditTraingClassFinish.newBuilder()
                                .resultCode(EventEditTraingClassFinish.RESULT_CANCEL)
                                .build());
                        EventBus.getDefault().post(EventCopyTraingClassFinish.newBuilder()
                                .resultCode(EventCopyTraingClassFinish.RESULT_CANCEL)
                                .build());
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .create()
                .show();
    }

    @OnClick({R.id.confirmDateTipIv, R.id.platformDividendLayout, R.id.courseScheduleLayout, R.id.titleBackBtn, R.id.interestLayout, R.id.openBuyLayout, R.id.openClassConditionLayout, R.id.startClassDateLayout, R.id.endClassDateLayout, R.id.confirmDateLayout, R.id.classLocationLayout, R.id.suitableLearnAgeLayout, R.id.learnTargetLayout, R.id.suitableLearnPeopleLayout, R.id.tagLayout, R.id.traingCardLayout, R.id.nextBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.confirmDateTipIv:
                if (TextUtils.isEmpty(formModel.getMinClassSize())) {
                    CommonTipDialog.newInstance(StringUtils.getString(R.string.confirm_date_tip))
                            .show(getSupportFragmentManager(), "");
                } else {
                    CommonTipDialog.newInstance(String.format(StringUtils.getString(R.string.confirm_date_tip_template), formModel.getMinClassSize()))
                            .show(getSupportFragmentManager(), "");
                }
                break;
            case R.id.courseScheduleLayout:
                ARouter.getInstance()
                        .build(ARouterConfig.CourseSchedulePage)
                        .withParcelable("courseScheduleModel", formModel.getCourseScheduleModel())
                        .navigation(this, REQUEST_CODE_INPUT_COURSE_SCHEDULE);
                containerLayout.requestFocus();
                break;

            case R.id.titleBackBtn:
                CancelEditDialogUtil.newbuilder(this)
                        .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                finish();
                                EventBus.getDefault().post(EventEditTraingClassFinish.newBuilder()
                                        .resultCode(EventEditTraingClassFinish.RESULT_CANCEL)
                                        .build());
                                EventBus.getDefault().post(EventCopyTraingClassFinish.newBuilder()
                                        .resultCode(EventCopyTraingClassFinish.RESULT_CANCEL)
                                        .build());
                            }
                        })
                        .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        })
                        .create()
                        .show();
                break;
            case R.id.interestLayout:
                ARouter.getInstance()
                        .build(ARouterConfig.PublishSelectInterestPage)
                        .navigation(this, REQUEST_CODE_SELECT_INTEREST);
                containerLayout.requestFocus();
                break;
            case R.id.openBuyLayout:
                openBuyDialog.show(getSupportFragmentManager(), "");
                containerLayout.requestFocus();
                break;
            case R.id.openClassConditionLayout:
                openClassConditionDialog.show(getSupportFragmentManager(), "");
                containerLayout.requestFocus();
                break;
            case R.id.startClassDateLayout: {
                Calendar selectedDate = Calendar.getInstance();
                Calendar startDate = Calendar.getInstance();
                Calendar endDate = Calendar.getInstance();
                endDate.add(Calendar.YEAR, 100);
                startDate.add(Calendar.DAY_OF_YEAR, 1);
                if (formModel.getStartClassDate() != null) {
                    selectedDate.setTimeInMillis(formModel.getStartClassDate());
                } else {
                    selectedDate.setTimeInMillis(startDate.getTimeInMillis());
                }
                //时间选择器
                TimePickerView pickerView = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        if (formModel.getStartClassDate() == null || formModel.getStartClassDate() != date.getTime()) {
                            formModel.setStartClassDate(date.getTime());
                            formModel.setEndClassDate(null);
                            formModel.setConfirmDate(null);
                            updateView();
                        }
                    }
                })
                        //年月日时分秒 的显示与否，不设置则默认全部显示
                        .setType(new boolean[]{true, true, true, false, false, false})
                        .setSubmitText(getString(R.string.finish))
                        .setTitleBgColor(Color.WHITE)
                        .setBgColor(0xfff0f0f0)
                        .setLabel("", "", "", "", "", "")
                        .isCenterLabel(false)
                        .setDividerColor(Color.DKGRAY).setSubmitColor(ColorUtil.getColor(R.color.zwcolor_pink_f93684))
                        .setCancelColor(ColorUtil.getColor(R.color.zwcolor_pink_f93684))
                        .setContentSize(21)
                        .setDate(selectedDate)
                        .setRangDate(startDate, endDate)
                        .isDialog(true)
                        .build();
                pickerView.show();
                containerLayout.requestFocus();
                break;
            }
            case R.id.endClassDateLayout: {
                Calendar selectedDate = Calendar.getInstance();
                Calendar startDate = Calendar.getInstance();
                Calendar endDate = Calendar.getInstance();
                startDate.setTimeInMillis(formModel.getStartClassDate());
                endDate.setTimeInMillis(startDate.getTimeInMillis());
                endDate.add(Calendar.YEAR, 50);
                if (formModel.getEndClassDate() != null) {
                    selectedDate.setTimeInMillis(formModel.getEndClassDate());
                } else {
                    selectedDate.setTimeInMillis(startDate.getTimeInMillis());
                }
                //时间选择器
                TimePickerView pickerView = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        formModel.setEndClassDate(date.getTime());
                        updateView();
                    }
                })
                        //年月日时分秒 的显示与否，不设置则默认全部显示
                        .setType(new boolean[]{true, true, true, false, false, false})
                        .setSubmitText(getString(R.string.finish))
                        .setTitleBgColor(Color.WHITE)
                        .setBgColor(0xfff0f0f0)
                        .setLabel("", "", "", "", "", "")
                        .isCenterLabel(false).setSubmitColor(ColorUtil.getColor(R.color.zwcolor_pink_f93684))
                        .setCancelColor(ColorUtil.getColor(R.color.zwcolor_pink_f93684))
                        .setDividerColor(Color.DKGRAY)
                        .setContentSize(21)
                        .setDate(selectedDate)
                        .setRangDate(startDate, endDate)
                        .isDialog(true)
                        .build();
                pickerView.show();
                containerLayout.requestFocus();
                break;
            }
            case R.id.confirmDateLayout: {
                Calendar selectedDate = Calendar.getInstance();
                Calendar startDate = Calendar.getInstance();
                Calendar endDate = Calendar.getInstance();
                endDate.setTimeInMillis(formModel.getStartClassDate());
                endDate.add(Calendar.DAY_OF_YEAR, -1);
                if (startDate.after(endDate)) {
                    startDate.setTimeInMillis(endDate.getTimeInMillis());
                }
                if (formModel.getConfirmDate() != null) {
                    selectedDate.setTimeInMillis(formModel.getConfirmDate());
                } else {
                    selectedDate.setTimeInMillis(endDate.getTimeInMillis());
                }
                //时间选择器
                TimePickerView pickerView = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        formModel.setConfirmDate(date.getTime());
                        updateView();
                    }
                })
                        //年月日时分秒 的显示与否，不设置则默认全部显示
                        .setType(new boolean[]{true, true, true, false, false, false})
                        .setSubmitText(getString(R.string.finish))
                        .setTitleBgColor(Color.WHITE)
                        .setBgColor(0xfff0f0f0)
                        .setLabel("", "", "", "", "", "")
                        .isCenterLabel(false).setSubmitColor(ColorUtil.getColor(R.color.zwcolor_pink_f93684))
                        .setCancelColor(ColorUtil.getColor(R.color.zwcolor_pink_f93684))
                        .setDividerColor(Color.DKGRAY)
                        .setContentSize(21)
                        .setDate(selectedDate)
                        .setRangDate(startDate, endDate)
                        .isDialog(true)
                        .build();
                pickerView.show();
                containerLayout.requestFocus();
                break;
            }
            case R.id.classLocationLayout:
                ARouter.getInstance()
                        .build(ARouterConfig.SelectLocationPage)
                        .navigation(this, REQUEST_CODE_SELECT_CLASS_LOCATION);
                containerLayout.requestFocus();
                break;
            case R.id.suitableLearnAgeLayout:
                ARouter.getInstance()
                        .build(ARouterConfig.SelectSuitableLearnAgePage)
                        .withString("channel", formModel.getPublishInterestItem().getParent().getId())
                        .withObject("preSelectedArray", formModel.getSuitableLearnAgeItemList().toArray())
                        .navigation(this, REQUEST_CODE_SELECT_SUITABLE_LEARN_AGE);
                containerLayout.requestFocus();
                break;
            case R.id.learnTargetLayout:
                ARouter.getInstance()
                        .build(ARouterConfig.SelectLearnTargetPage)
                        .withObject("preSelectedArray", formModel.getSelectLearnTargetItemList().toArray())
                        .withString("channel", formModel.getPublishInterestItem().getParent().getId())
                        .navigation(this, REQUEST_CODE_SELECT_LEARN_TARGET);
                containerLayout.requestFocus();
                break;
            case R.id.suitableLearnPeopleLayout:
                ARouter.getInstance()
                        .build(ARouterConfig.SelectSuitablePeoplePage)
                        .withParcelable("preSelected", formModel.getSelectSuitablePeopleItem())
                        .withString("channel", formModel.getPublishInterestItem().getParent().getId())
                        .navigation(this, REQUEST_CODE_SELECT_SUITABLE_PEOPLE);
                containerLayout.requestFocus();
                break;
            case R.id.tagLayout:
                if (formModel.getSelectTagItemList().size() < PublishUtil.MAX_PUBLISH_TAG_NUM) {
                    String[] selectedIds = new String[formTagAdapter.getData().size()];
                    for (int i = 0; i < selectedIds.length; ++i) {
                        selectedIds[i] = formTagAdapter.getData().get(i).getId();
                    }
                    ARouter.getInstance()
                            .build(ARouterConfig.SelectTagPage)
                            .withObject("selectedIds", selectedIds)
                            .navigation(this, REQUEST_CODE_SELECT_TAG);
                } else {
                    ToastX.show(String.format(getString(R.string.reach_max_tag_select_num), PublishUtil.MAX_PUBLISH_TAG_NUM));
                }
                containerLayout.requestFocus();
                break;
            case R.id.traingCardLayout: {
                ARouter.getInstance()
                        .build(ARouterConfig.SelectTraingCardPage)
                        .withObject("selectedCards", formModel.getTraingCardList())
                        .navigation(this, REQUEST_CODE_SELECT_TRAING_CARD);
                containerLayout.requestFocus();
                break;
            }
            case R.id.nextBtn:
                if (checkFormValidate()) {
                    ARouter.getInstance()
                            .build(ARouterConfig.CourseDescriptionPage)
                            .withParcelable("traingClassFormModel", formModel)
                            .navigation(this, REQUEST_CODE_NEXT);
                }
                break;
        }
    }

    public void disableDateSelect() {
        UIHelper.setViewAndChildrenEnabled(endClassDateLayout, false);
        UIHelper.setViewAndChildrenEnabled(confirmDateLayout, false);
    }

    public void enableDateSelect() {
        UIHelper.setViewAndChildrenEnabled(endClassDateLayout, true);
        UIHelper.setViewAndChildrenEnabled(confirmDateLayout, true);
    }

    public void disableTagSelect() {
        UIHelper.setViewAndChildrenEnabled(suitableLearnAgeLayout, false);
        UIHelper.setViewAndChildrenEnabled(learnTargetLayout, false);
        UIHelper.setViewAndChildrenEnabled(suitableLearnPeopleLayout, false);
    }

    public void enableTagSelect() {
        UIHelper.setViewAndChildrenEnabled(suitableLearnAgeLayout, true);
        UIHelper.setViewAndChildrenEnabled(learnTargetLayout, true);
        UIHelper.setViewAndChildrenEnabled(suitableLearnPeopleLayout, true);
    }

    public void clearTagSelect() {
        formModel.setSelectSuitablePeopleItem(SelectSuitablePeopleItem.newBuilder().build());
        formModel.setSelectLearnTargetItemList(new LinkedList<SelectLearnTargetItem>());
        formModel.setSuitableLearnAgeItemList(new LinkedList<SuitableLearnAgeItem>());
    }


}
